package jwm.data;

import jwm.event.Event;
import jwm.event.EventListener;
import jwm.event.ExceptionEvent;
import jwm.event.URLLoaderEvent;
import jwm.network.ThreadLoader;

public class PageSearcher implements EventListener {

   private RatedURL url;
   private URLQueue queue;
   private ThreadLoader loader;
   private Proccessor proccessor;
   
   public PageSearcher(RatedURL url, URLQueue queue, Proccessor proccessor) {
      System.out.println(url);
      this.queue = queue;
      this.url = url;
      this.proccessor = proccessor;
      loader = new ThreadLoader();
      loader.addEventListener(this);
      loader.load(url.getUrl());
   }

   @Override
   public void receiveEvent(Event event) {
      if (event instanceof URLLoaderEvent) {
         loader.removeEventListener(this);
         URLLoaderEvent loaderEvent = (URLLoaderEvent) event;
         searchStart(loaderEvent.getData());
      } else if (event instanceof ExceptionEvent) {
         queue.add(url);
      }
   }
   
   private void searchStart(String subPage) {
      String tag = "<a";
      int index = subPage.indexOf(tag);
      if (index != -1) {
         searchEnd(subPage.substring(index + tag.length()));
      } else {
         synchronized (proccessor) {            
            proccessor.notify();
         }
         return;
      }
   }
   
   private void searchEnd(String subPage) {
      String tag = "</a";
      int index = subPage.indexOf(tag);
      if (index != -1) {
         AElement element = new AElement(subPage.substring(0, index), url.getUrl());
         if (element.isPDF()) {
            RatedURL rurl = new RatedURL(element.getUrl());
            if (!queue.contains(rurl)) {
               System.out.println(rurl.getUrl());
               queue.addPassed(rurl);
            }
         } else if (element.isValid()) {
            RatedURL rurl = new RatedURL(element.getUrl());
            if (!queue.contains(rurl)) {
               queue.add(rurl);
            }
         }
         searchStart(subPage.substring(index + tag.length()));
      } else {
         synchronized (proccessor) {            
            proccessor.notify();
         }
         return;
      }
   }

}
